package pers.lance.fsm.ssh;

import java.io.*;
import java.net.Socket;

public class Client {
    Socket socket = null;
    String host;
    int port;
    InputStream in = null;
    BufferedReader read = null;
    OutputStream outputStream = null;
    PrintWriter printWriter = null;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;

    }

    public boolean connect() {
        try {
            socket = new Socket(host, port);
            in = socket.getInputStream();
            read = new BufferedReader(new InputStreamReader(in));
            outputStream = socket.getOutputStream();
            printWriter = new PrintWriter(outputStream);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    public void sendMessage(String str) {
        printWriter.print(str+"\n");
        printWriter.flush();
    }

    public void close() {
        printWriter.close();
        try {
            outputStream.close();
            read.close();
            in.close();
            socket.shutdownOutput();
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getMessage(){
        try {
            return  read.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void finalize() throws Throwable {
        close();
        super.finalize();
    }
}
